/**
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: 联动优势科技有限公司</p>
 * <p>Apr 25, 20131:50:12 PM</p>
 * @author Ding Zhe
 * @version 1.0
 */
package com.umpay.privi.ejb.sys;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.umpay.common.persist.ibatis.DataAccessException;
import com.umpay.privi.common.BeanManager;
import com.umpay.privi.common.Constants;
import com.umpay.privi.common.ReqMessage;
import com.umpay.privi.common.ResMessage;
import com.umpay.privi.common.RetCode;
import com.umpay.privi.common.XmlData;
import com.umpay.privi.dao.on.sys.GroupUserRelDao;
import com.umpay.privi.dao.on.sys.UserDao;
import com.umpay.privi.dao.on.sys.UserGroupDao;
import com.umpay.privi.dao.on.sys.UserMediaDao;
import com.umpay.privi.dao.on.sys.UserRoleDao;
import com.umpay.privi.exception.BusinessException;
import com.umpay.privi.helper.ReqParaCheckHelper;
import com.umpay.privi.model.sys.GroupUserRel;
import com.umpay.privi.model.sys.User;
import com.umpay.privi.model.sys.UserGroup;
import com.umpay.privi.model.sys.UserMedia;
import com.umpay.privi.model.sys.UserRole;
import com.umpay.privi.service.sys.UserServiceRemote;
import com.umpay.privi.util.ListUtil;
import com.umpay.privi.util.PasswordUtil;
import com.umpay.privi.util.SeqUtil;
import com.umpay.privi.util.StringUtil;

/** 
 * desc:
 * <p>创建人：Ding Zhe 创建日期：Apr 25, 2013 </p>
 * @version V1.0  
 */
@TransactionManagement(TransactionManagementType.BEAN)
@SuppressWarnings("unchecked")
public class UserServiceBean implements UserServiceRemote{
	private static Logger logger = LoggerFactory.getLogger(UserServiceBean.class); 
	private UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
	private UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
	
	public ResMessage login(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]login请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.login.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String mediaId = StringUtil.trim(reqMessage.getString(XmlData.MEDIAID));
			String password = StringUtil.trim(reqMessage.getString(XmlData.PASSWORD));
			String smsFlag = StringUtil.trim(reqMessage.getString("smsFlag"));
			if(StringUtil.isEmpty(smsFlag) && StringUtil.isEmpty(password)){
				throw new BusinessException(RetCode.REQ_PARA_MISSING,"参数[password][smsFlag]二者必填一项");
			}
			//通过媒介获取userId
			UserMedia userMedia = userMediaDao.getByMediaIdAndSysId(mediaId,sysId);
			if(userMedia==null) {
				throw new BusinessException(RetCode.NO_DATA, "用户媒介不存在");
			}
			
			//获取用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put(XmlData.USERID, userMedia.getUserId());
			qryMap.put(XmlData.SYSID, sysId);
			qryMap.put(XmlData.STATE, "0");
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);		
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "用户不存在");
			}
			
			if (!smsFlag.equals("1")){ //手机验证码登录不验证密码
				//判断数据库中上送密码是否一致
				if (!StringUtil.trim(user.getPassword()).equals(password)) {
					throw new BusinessException(RetCode.OLD_PWD_ERROR, "原密码输入有误");
				}
			}
			
			/*//判断数据库中上次修改密码的时间是否过期(三个月)
			if(user.getPasswdLastModifyTime()!=null){
				Timestamp passwdLastModifyTime = user.getPasswdLastModifyTime();
				boolean parseBool = TimeUtils.parseTime(passwdLastModifyTime);
				if(parseBool==false){
					throw new BusinessException(RetCode.OLD_PWD_ERROR, "密码超过有效期");
				}
			}else{
				throw new BusinessException(RetCode.OLD_PWD_ERROR, "密码超过有效期");
			}*/
			
			//得到上次登录时间
			user.setLastLoginTime(user.getLastLoginTime());
			
			//更新登录时间
			int count = userDao.updateLoginTime(sysId,userMedia.getUserId());
			if(count != 1){
				throw new BusinessException(RetCode.NO_DATA, "修改的用户信息不存在");
			}
			resMessage.put(XmlData.USER_MEDIA_INFO, userMedia);
			resMessage.put(XmlData.USER_INFO, user);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("用户登录成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]login响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage logout(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]logout请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.logout.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String userId =  StringUtil.trim(reqMessage.getString(XmlData.USERID));
			
			//更新登出时间
			int count = userDao.updateLogoutTime(sysId,userId);
			if(count != 1){
				throw new BusinessException(RetCode.NO_DATA, "用户不存在");
			}
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("用户登出成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]logout响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage queryUsers(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]queryUsers请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.queryUserList.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String operRank=(String)reqMessage.get(XmlData.OPERRANK);
			List<String> roleIdList=(List<String>)reqMessage.get(XmlData.ROLEID_LIST);
			//0：超级管理员；1：系统管理员；2：管理员；3：操作员；
			if(!operRank.equals(Constants.RANK_SUPER_ADMIN)
					&&!operRank.equals(Constants.RANK_SYS_ADMIN)
					&&!operRank.equals(Constants.RANK_ADMIN)){
				throw new BusinessException(RetCode.NO_PRIVILEGE,"无操作权限");
			}
			if(roleIdList!=null&&roleIdList.size()!=0){//如果roleIdList不为空
				reqMessage.put(XmlData.ROLEID_LIST,ListUtil.joinAs(roleIdList,","));
			}
			Map<String, Object> reqMap=reqMessage.getReqMap();
			List<User> users = userDao.findUserListByKeys(reqMap);
			resMessage.put(XmlData.RESULT_LIST, users);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("查询用户成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}
	//根据用户组分页查询用户
	public ResMessage queryUsersForPageByUserGroup(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]queryUsersForPageByUserGroup请求数据："+reqMessage);
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {	
			Integer startIndex = Integer.parseInt(reqMessage.get(XmlData.START_INDEX).toString());//开始记录索引
			Integer pageSize = Integer.parseInt(reqMessage.get(XmlData.PAGE_SIZE).toString());//每页显示条数
			Object obj=reqMessage.get(XmlData.ROLEID_LIST);
			if(obj!=null){//如果roleIdList不为空
				List<String> roleList=(List<String>)reqMessage.get(XmlData.ROLEID_LIST);
				reqMessage.put(XmlData.ROLEID_LIST,ListUtil.joinAs(roleList,","));
			}
			Map<String, Object> reqMap=reqMessage.getReqMap();
			List<User> userList = userDao.findUserPageListByUserGroup(reqMap,startIndex,pageSize);
			Integer totalNum = userDao.findUserPageListByUserGroup_count(reqMap);
			resMessage.put(XmlData.RESULT_LIST, userList);
			resMessage.put(XmlData.TOTAL_NUM, totalNum);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]queryUsersForPageByUserGroup响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage queryUsersForPage(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]queryUsersForPage请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.queryUsersForPage.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {	
			
			Integer startIndex = Integer.parseInt(reqMessage.get(XmlData.START_INDEX).toString());//开始记录索引
			Integer pageSize = Integer.parseInt(reqMessage.get(XmlData.PAGE_SIZE).toString());//每页显示条数
			String operRank=(String)reqMessage.get(XmlData.OPERRANK);
			List<String> roleIdList=(List<String>)reqMessage.get(XmlData.ROLEID_LIST);
			//0：超级管理员、1：系统管理员、2：管理员有操作权限，3：操作员无操作权限
			if(!operRank.equals(Constants.RANK_SUPER_ADMIN)
					&&!operRank.equals(Constants.RANK_SYS_ADMIN)
					&&!operRank.equals(Constants.RANK_ADMIN)){
				throw new BusinessException(RetCode.NO_PRIVILEGE,"无操作权限");
			}
			if(roleIdList!=null&&roleIdList.size()!=0){//如果roleIdList不为空
				List<String> roleList=(List<String>)reqMessage.get(XmlData.ROLEID_LIST);
				reqMessage.put(XmlData.ROLEID_LIST,ListUtil.joinAs(roleList,","));
			}
			if(operRank.equals(Constants.RANK_ADMIN)){//管理员查询同组的操作员
				String operUserId =  StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
				GroupUserRelDao groupUserRelDao = BeanManager.getBean("groupUserRelDao",GroupUserRelDao.class);
				Map<String, Object> qryMap=new HashMap<String, Object>();
				qryMap.put(XmlData.USERID,operUserId);
				List<GroupUserRel> groupUserList=groupUserRelDao.queryListByKeys(qryMap);
				StringBuilder groupIdList=new StringBuilder();
				for (int i = 0; i < groupUserList.size(); i++) {
					if(groupUserList.size()!= i+1){ 
						groupIdList.append(groupUserList.get(i).getUserGroupId()).append(",");
					}else{
						groupIdList.append(groupUserList.get(i).getUserGroupId());//最后一个拼接去逗号
					}
				}
				reqMessage.put(XmlData.USERGROUPIDLIST,groupIdList);//设置查询同组groupId
			}
			Map<String, Object> reqMap=reqMessage.getReqMap();
			List<Map<String,Object>>  userList = userDao.findUsersForPage(reqMap,startIndex,pageSize);
			Integer totalNum = userDao.findUserPageList_count(reqMap);
			resMessage.put(XmlData.RESULT_LIST, userList);
			resMessage.put(XmlData.TOTAL_NUM, totalNum);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("分页查询用户成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}
	
	public ResMessage isExistMedia(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]isExistMedia请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.isExistMedia.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {	
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String mediaId = StringUtil.trim(reqMessage.getString(XmlData.MEDIAID));
			
			//校验媒介是否存在
			logger.info(String.format("根据用户媒介查询媒介信息： mediaId=%s,sysId=%s",mediaId,sysId));
			UserMedia userMedia = userMediaDao.getByMediaIdAndSysId(mediaId, sysId);
			logger.info("根据用户媒介查询媒介信息返回结果： " + userMedia);
			String flag = "0";
			if (userMedia != null) {
				flag = "1";
			}
			
			resMessage.put(XmlData.FLAG, flag);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("校验媒介是否存在成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}

	
	public ResMessage addUser(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]addUser请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.addUser.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		GroupUserRelDao groupUserRelDao = BeanManager.getBean("groupUserRelDao",GroupUserRelDao.class);
		UserGroupDao userGroupDao = BeanManager.getBean("userGroupDao",UserGroupDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			Short shortSysId = StringUtil.isEmpty(sysId) ? null : Short.parseShort(sysId);
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String mediaId = StringUtil.trim(reqMessage.getString(XmlData.MEDIAID));
			String password = StringUtil.trim(reqMessage.getString(XmlData.PASSWORD));
			String userName = StringUtil.trim(reqMessage.getString(XmlData.USERNAME));
			String sex = StringUtil.trim(reqMessage.getString(XmlData.SEX));
			Short shortSex = StringUtil.isEmpty(sex) ? null : Short.parseShort(sex);
			String email = StringUtil.trim(reqMessage.getString(XmlData.EMAIL));
			String mobileId = StringUtil.trim(reqMessage.getString(XmlData.MOBILEID));
			String telephoneNo = StringUtil.trim(reqMessage.getString(XmlData.TELEPHONENO));
			String rank = (String) reqMessage.get(XmlData.RANK);
			Short shortRank = StringUtil.isEmpty(rank) ? null : Short.parseShort(rank);
			List<Map<String, String>> roleList = (List<Map<String, String>>) reqMessage.get(XmlData.ROLE_LIST);
			
			String userId = String.valueOf(SeqUtil.genSequence(Constants.USER_SEQ) + 100);
			if (password.length() > 32) {
				throw new BusinessException(RetCode.LOGINPWD_TOO_LEN, "密码长度不能大于32！");
			}
			
			//校验媒介是否存在
			logger.info(String.format("根据用户媒介查询媒介信息： mediaId=%s,sysId=%s",mediaId,sysId));
			UserMedia userMedia = userMediaDao.getByMediaIdAndSysId(mediaId, sysId);
			logger.info("根据用户媒介查询媒介信息返回结果： " + userMedia);
			if (userMedia != null) {
				throw new BusinessException(RetCode.IS_EXIST_USERMEDIA, "用户媒介已存在");
			}
			
			//查询操作用户的媒介信息
			UserMedia operUserMedia = userMediaDao.get(operUserId, "4");
			if (operUserMedia == null) {
				throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "操作用户用户媒介不存在");
			}
			//add by bitao 2016-11-1 增加手机号校验 start
			if (StringUtil.isNotEmpty(mobileId)){
				//查询手机号是否存在
				Map<String, Object> qryMapMbile = new HashMap<String, Object>();
				qryMapMbile.put(XmlData.MOBILEID, mobileId);
				int count = userDao.findPageList_count(qryMapMbile);
				if (count>=1){
					throw new BusinessException(RetCode.IS_EXIST_MOBILEID, "手机号已经存在");
				}
			}
			//add by bitao 2016-11-1 增加手机号校验 end
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + operUser);
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "用户不存在");
			}
			//业务管理员添加业务操作员&系统管理员添加业务操作员,所添加的用戶属于本组
			if ((operUser.getRank() == 2 && shortRank == 3) || (operUser.getRank() == 1 && shortRank == 3)) { 
				logger.info("查询用户组：openUserId=" + operUserId + ",sysId=" + sysId);
				List<UserGroup> list = userGroupDao.queryList(null, operUserId, sysId);
				logger.info("查询用户组信息返回结果：" + list);
				if (list == null || list.size() == 0) {
					throw new BusinessException(RetCode.NO_USERGROUP, "操作用户不在任何用户组内");
				}
				Integer userGroupId = list.get(0).getUserGroupId();
				logger.info("添加用户用户组关系：userGroupId" + userGroupId + ",userId=" + userId + ",sysId=" + sysId);
				groupUserRelDao.add(userGroupId.toString(), userId, sysId);
				
				//添加用户角色
				for (Map<String, String> role : roleList) {
					String roleId = StringUtil.trim((String) role.get(XmlData.ROLE_ID));
					
					UserRole userRole = new UserRole();
					userRole.setUserId(userId);
					userRole.setRoleId(Integer.parseInt(roleId));
					userRole.setIsAssignable((short) 1); //不可分配
					userRole.setIsUsable((short) 0); //可使用
					userRole.setFlag((short) 0);	
					logger.info("添加用户角色关系：" + userRole);
					userRoleDao.insert(userRole);
				}
			
			//系统管理员添加业务管理员，生成新的组，把用户加入在此组中
			} else if (operUser.getRank() == 1 && shortRank == 2) { 
				Integer userGroupId = SeqUtil.genSequence(Constants.USER_GROUP_SEQ) + 100;
				logger.info("添加用户用户组关系：userGroupId" + userGroupId + ",userId=" + userId + ",sysId=" + sysId);
				groupUserRelDao.add(userGroupId.toString(), userId, sysId);
				
				logger.info("查询用户组查询：openUserId=" + operUserId + ",sysId=" + sysId);
				List<UserGroup> list = userGroupDao.queryList(null, operUserId, sysId);
				logger.info("查询用户信息返回结果：" + list);
				if (list == null || list.size() == 0) {
					throw new BusinessException(RetCode.NO_USERGROUP, "操作用户不在任何用户组内");
				}
				UserGroup operUserGroup = list.get(0);
				Integer operUserGroupId = operUserGroup.getUserGroupId();
				
				UserGroup userGroup = new UserGroup();
				userGroup.setUserGroupId(userGroupId);
				userGroup.setUserGroupName("系统生成");
				userGroup.setParentId(operUserGroupId);
				userGroup.setDescription("系统生成");
				userGroup.setIsLeaf((short)0);
				userGroup.setSysId(shortSysId);
				userGroup.setCreator(operUserMedia.getMediaId());
				userGroup.setModUser(operUserMedia.getMediaId());
				logger.info("添加用户组信息：" + userGroup);
				userGroupDao.insert(userGroup);	
				
				//添加一个可使用的角色
				UserRole userRole = new UserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(3); //业务管理员的默认角色
				userRole.setIsAssignable((short) 1); //不可分配
				userRole.setIsUsable((short) 0); //可使用
				userRole.setFlag((short) 0); //正常	
				logger.info("添加用户角色关系：" + userRole);
				userRoleDao.insert(userRole);
				
				//添加用户角色
				for (Map<String, String> role : roleList) {
					String roleId = StringUtil.trim((String) role.get(XmlData.ROLE_ID));
					
					UserRole userRole1 = new UserRole();
					userRole1.setUserId(userId);
					userRole1.setRoleId(Integer.parseInt(roleId));
					userRole1.setIsAssignable((short) 0); //可分配
					userRole1.setIsUsable((short) 1); //不可使用
					userRole1.setFlag((short) 0); //正常
					logger.info("添加用户角色关系：" + userRole1);
					userRoleDao.insert(userRole1);
				}		
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}
			
			//添加用户
			User userInf = new User();
			userInf.setUserId(userId);
			userInf.setPassword(password);
			userInf.setUserName(userName);
			userInf.setSex(shortSex);
			userInf.setEmail(email);
			userInf.setMobileId(mobileId);
			userInf.setTelephoneNo(telephoneNo);
			userInf.setRank(shortRank);
			userInf.setCreator(operUserMedia.getMediaId());
			userInf.setModUser(operUserMedia.getMediaId());
			userInf.setSysId(shortSysId);
			logger.info("添加用户信息：" + userInf);
			userDao.insert(userInf);
			
			//添加用户媒介
			UserMedia media = new UserMedia();
			media.setUserId(userId);
			media.setMediaType("4");
			media.setMediaId(mediaId);
			media.setSysId(shortSysId);
			media.setFlag((short)0);
			logger.info("添加用户媒介信息：" + media);
			userMediaDao.insert(media);
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("添加用户成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]addUser响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage modifyUser(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]updateUser请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.updateUser.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		UserGroupDao userGroupDao = BeanManager.getBean("userGroupDao",UserGroupDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			Short shortSysId = StringUtil.isEmpty(sysId) ? null : Short.parseShort(sysId);
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			String mediaId = StringUtil.trim(reqMessage.getString(XmlData.MEDIAID));
			String userName = StringUtil.trim(reqMessage.getString(XmlData.USERNAME));
			String sex = StringUtil.trim(reqMessage.getString(XmlData.SEX));
			Short shortSex = StringUtil.isEmpty(sex) ? null : Short.parseShort(sex);
			String email = StringUtil.trim(reqMessage.getString(XmlData.EMAIL));
			String mobileId = StringUtil.trim(reqMessage.getString(XmlData.MOBILEID));
			String telephoneNo = StringUtil.trim(reqMessage.getString(XmlData.TELEPHONENO));
			String state = StringUtil.trim((String) reqMessage.get(XmlData.STATE));
			Short shortState = StringUtil.isEmpty(state) ? null : Short.parseShort(state);
			List<Map<String, String>> newRoleIdList = (List<Map<String, String>>) reqMessage.get(XmlData.ROLE_LIST); 
			
			//如果媒介不为空，则需要修改媒介信息,校验媒介是否存在
			if (StringUtil.isNotEmpty(mediaId)) {
				UserMedia userMedia = userMediaDao.getByMediaIdAndSysId(mediaId, sysId);
				if (userMedia != null) {
					throw new BusinessException(RetCode.IS_EXIST_USERMEDIA, "用户媒介已存在");
				}
			}
			
			//查询操作用户的媒介信息
			UserMedia operUserMedia = userMediaDao.get(operUserId, "4");
			if (operUserMedia == null) {
				throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "操作用户用户媒介不存在");
			}
			
			Map<String, Object> qryMap = new HashMap<String, Object>();
			//获取操作用户信息
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询操作用户信息：" + qryMap);	
			User operUser = userDao.getUser(qryMap);	
			logger.info("查询操作用户信息返回结果：" + operUser);		
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询被操作用户信息：" + qryMap);	
			User user = userDao.getUser(qryMap);	
			logger.info("查询被操作用户信息返回结果：" + operUser);
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			logger.info("查询操作用户所属用户组：openUserId=" + operUserId + ",sysId=" + sysId);
			List<UserGroup> operList = userGroupDao.queryList(null, operUserId, sysId);
			logger.info("查询操作用户所属用户组返回结果：" + operList);
			if (operList == null || operList.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "操作用户不在任何用户组内");
			}
			Integer operUserGroupId = operList.get(0).getUserGroupId();
			
			logger.info("查询被操作用户所属用户组：userId=" + userId + ",sysId=" + sysId);
			List<UserGroup> list = userGroupDao.queryList(null, userId, sysId);
			logger.info("查询被操作用户所属用户组返回结果：" + operList);
			if (list == null || list.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "被操作用户不在任何用户组内");
			}
			Integer userGroupId = list.get(0).getUserGroupId();
			
			//系统管理员修改业务管理员&系统管理员修改操作员(操作员必须同组)&业务管理员修改操作员
			if ((operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3 && operUserGroupId.equals(userGroupId)) 
					|| (operUser.getRank() == 2 && user.getRank() == 3)) {
				/*
				 * 根据lastRoleIdList和newRoleIdList获取本次要添加的销售产品列表和要删除的销售产品列表
				 */
				qryMap.clear();
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.ROLETYPE, "2");
				logger.info("查询用户角色列表：" + qryMap);
				List<Map<String, Object>> lastRoleList = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户角色列表返回结果：" + lastRoleList);
				getAddAndDelRoleList(lastRoleList, newRoleIdList);
				
				//系统管理员修改操作员(操作员必须同组)&业务管理员修改操作员
				if ((operUser.getRank() == 1 && user.getRank() == 3 && operUserGroupId.equals(userGroupId)) 
						|| (operUser.getRank() == 2 && user.getRank() == 3)) {
					//添加用户角色
					for (Map<String, String> role : newRoleIdList) {
						String roleId = StringUtil.trim((String) role.get(XmlData.ROLE_ID));
						
						UserRole userRole = new UserRole();
						userRole.setUserId(userId);
						userRole.setRoleId(Integer.parseInt(roleId));
						userRole.setIsAssignable((short) 1); //不可分配
						userRole.setIsUsable((short) 0); //可使用
						userRole.setFlag((short)0);				
						try {
							logger.info("添加用户角色关系：" + userRole);	
							userRoleDao.insert(userRole);
						} catch (Exception e) {
							qryMap.clear();
							qryMap.put(XmlData.USERID, userId);
							qryMap.put(XmlData.ROLE_ID, roleId.toString());
							qryMap.put(XmlData.SYSID, sysId);
							qryMap.put(XmlData.ISASSIGNABLE, "1");
							qryMap.put(XmlData.ISUSABLE, "0");
							qryMap.put(XmlData.FLAG, "0");
							logger.info("修改用户角色关系：" + qryMap);
							userRoleDao.update(qryMap);
						}
					}
					
					//删除用户角色
					for (Map<String, Object> role : lastRoleList) {
						Integer roleId = (Integer) role.get(XmlData.ROLE_ID);
						
						qryMap.clear();
						qryMap.put(XmlData.USERID, userId);
						qryMap.put(XmlData.ROLE_ID, roleId.toString());
						qryMap.put(XmlData.SYSID, sysId);
						qryMap.put(XmlData.ISASSIGNABLE, "1");
						qryMap.put(XmlData.ISUSABLE, "0");
						qryMap.put(XmlData.FLAG, "1");
						logger.info("修改用户角色状态：" + qryMap);
						userRoleDao.update(qryMap);
					}
					
				//系统管理员修改业务管理员
				} else {
					//添加用户角色
					for (Map<String, String> role : newRoleIdList) {
						String roleId = StringUtil.trim((String) role.get(XmlData.ROLE_ID));
						
						UserRole userRole = new UserRole();
						userRole.setUserId(userId);
						userRole.setRoleId(Integer.parseInt(roleId));
						userRole.setIsAssignable((short) 0);
						userRole.setIsUsable((short) 1);
						userRole.setFlag((short) 0);				
						try {
							logger.info("添加用户角色关系：" + userRole);	
							userRoleDao.insert(userRole);
						} catch (Exception e) {
							qryMap.clear();
							qryMap.put(XmlData.USERID, userId);
							qryMap.put(XmlData.ROLE_ID, roleId.toString());
							qryMap.put(XmlData.SYSID, sysId);
							qryMap.put(XmlData.ISASSIGNABLE, "0");
							qryMap.put(XmlData.ISUSABLE, "1");
							qryMap.put(XmlData.FLAG, "0");
							logger.info("修改用户角色关系：" + qryMap);
							userRoleDao.update(qryMap);
						}
					}
					
					//删除用户角色
					for (Map<String, Object> role : lastRoleList) {
						Integer roleId = (Integer) role.get(XmlData.ROLE_ID);
						
						qryMap.clear();
						qryMap.put(XmlData.USERID, userId);
						qryMap.put(XmlData.ROLE_ID, roleId.toString());
						qryMap.put(XmlData.SYSID, sysId);
						qryMap.put(XmlData.ISASSIGNABLE, "0");
						qryMap.put(XmlData.ISUSABLE, "1");
						qryMap.put(XmlData.FLAG, "1");
						logger.info("修改用户角色状态：" + qryMap);
						userRoleDao.update(qryMap);
					}
				}
			}
			
			//修改用户信息
			User userInf = new User();
			userInf.setUserId(userId);
			userInf.setUserName(userName);
			userInf.setSex(shortSex);
			userInf.setEmail(email);
			userInf.setMobileId(mobileId);
			userInf.setTelephoneNo(telephoneNo);
			userInf.setModUser(operUserMedia.getMediaId());
			userInf.setModTime(new Timestamp(System.currentTimeMillis()));
			userInf.setState(shortState);
			userInf.setSysId(shortSysId);
			logger.info("修改用户信息：" + userInf);
			userDao.update(userInf);
			
			//如果媒介不为空，则需要修改媒介信息
			if (StringUtil.isNotEmpty(mediaId)) {
				userMediaDao.update(userId, mediaId, "4", new Timestamp(System.currentTimeMillis()), sysId);
			}
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("修改用户成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]updateUser："+resMessage);
		return resMessage;
	}
	
	private void getAddAndDelRoleList(List<Map<String, Object>> lastRoleIdList, List<Map<String, String>> newRoleIdList) {
		Map<String, Object> lastRole = null;
		Map<String, String> newRole = null;
		
		//首先将用户已经拥有的角色列表和本次上送的角色列表重叠的部分去除，
		//上次用户已经拥有的角色列表列表即为要删除的角色列表
		//本次上送的角色列表列表即为要添加的角色列表
		for (int i = 0; i < lastRoleIdList.size(); i ++) {
			lastRole = lastRoleIdList.get(i);
			Integer lastRoleId = (Integer) lastRole.get(XmlData.ROLE_ID);
			for (int j = 0; j < newRoleIdList.size(); j ++) {
				newRole = newRoleIdList.get(j);
				String newRoleId = (String) newRole.get(XmlData.ROLE_ID);
				if (lastRoleId.toString().equals(newRoleId)) {
					lastRoleIdList.remove(i);
					i --;
					newRoleIdList.remove(j);
					j --;
					break;
				}
			}
		}
	}
	
	public ResMessage getUserDetail(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]getDetail请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.getDetail.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);	
			User operUser = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);	
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			//获取用户信息,超级管理员查询系统管理员&系统管理员查询业务员管理员&系统管理员查询业务操作员&业务管理员查询业务操作员
			if ((operUser.getRank() == 0 && user.getRank() == 1) 
					|| (operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3) 
					|| (operUser.getRank() == 2 && user.getRank() == 3)) {
				Map<String, Object> userInfo = new HashMap<String, Object>();
				userInfo.put(XmlData.USERNAME, user.getUserName());
				userInfo.put(XmlData.RANK, user.getRank());
				userInfo.put(XmlData.EMAIL, user.getEmail());
				userInfo.put(XmlData.MOBILEID,user.getMobileId());
				
				UserMedia userMedia = userMediaDao.get(user.getUserId(), "4");
				if (userMedia == null) {
					throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "用户媒介不存在");
				}
				userInfo.put(XmlData.MEDIAID, userMedia.getMediaId());
				
				resMessage.put(XmlData.USER_INFO, userInfo);
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}
			
			List<Map<String,Object>> roleList = null;
			//获取角色列表，系统管理员查询业务员管理员角色&系统管理员查询业务操作员角色&业务管理员查询业务操作员角色
			if ((operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3) 
					|| (operUser.getRank() == 2 && user.getRank() == 3)) {
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.ROLETYPE, "2");
				logger.info("查询用户业务角色列表：" + qryMap);
				roleList = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户业务角色列表返回结果：" + roleList);
				resMessage.put(XmlData.ROLE_LIST, roleList);
			}
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("查询用户详情成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]getDetail响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage viewUserPrivilege(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]previewUserPrivilege请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.viewUserPrivilege.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);	
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			//系统管理员查询业务员管理员&系统管理员查询业务操作员&业务管理员查询业务操作员
			if ((operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3) 
					|| (operUser.getRank() == 2 && user.getRank() == 3)) {
				Map<String, Object> userInfo = new HashMap<String, Object>();
				userInfo.put(XmlData.USERID, user.getUserId());
				userInfo.put(XmlData.USERNAME, user.getUserName());
				userInfo.put(XmlData.SEX, user.getSex());
				userInfo.put(XmlData.EMAIL, user.getEmail());
				userInfo.put(XmlData.MOBILEID, user.getMobileId());
				userInfo.put(XmlData.TELEPHONENO, user.getTelephoneNo());
				userInfo.put(XmlData.CREATOR, user.getCreator());
				userInfo.put(XmlData.MODUSER, user.getModUser());
				userInfo.put(XmlData.RANK, user.getRank());
				userInfo.put(XmlData.REGTIME, user.getRegTime());
				userInfo.put(XmlData.MODTIME, user.getModTime());
				userInfo.put(XmlData.STATE, user.getState());
				
				UserMedia userMedia = userMediaDao.get(user.getUserId(), "4");
				if (userMedia == null) {
					throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "用户媒介不存在");
				}
				userInfo.put(XmlData.MEDIAID, userMedia.getMediaId());
				
				resMessage.put(XmlData.USER_INFO, userInfo);
				
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.ROLETYPE, "2");
				logger.info("查询用户业务角色列表：" + qryMap);
				List<Map<String,Object>> roleList = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户业务角色列表返回结果：" + roleList);
				resMessage.put(XmlData.ROLE_LIST, roleList);
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("预览操作员权限成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]previewUserPrivilege响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage viewUserManager(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]viewUserManager请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.viewUserManager.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		UserGroupDao userGroupDao = BeanManager.getBean("userGroupDao",UserGroupDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);		
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			logger.info("查询用户组：openUserId=" + operUserId + ",sysId=" + sysId);
			List<UserGroup> operList = userGroupDao.queryList(null, operUserId, sysId);
			logger.info("查询用户信息返回结果：" + operList);
			if (operList == null || operList.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "操作用户不在任何用户组内");
			}
			Integer operUserGroupId = operList.get(0).getUserGroupId();
			
			logger.info("查询用户组：userId=" + userId + ",sysId=" + sysId);
			List<UserGroup> list = userGroupDao.queryList(null, userId, sysId);
			logger.info("查询用户信息返回结果：" + list);
			if (list == null || list.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "被操作用户不在任何用户组内");
			}
			Integer userGroupId = list.get(0).getUserGroupId();
			
			List<User> managerInfoList  = null;
			List<User> nextClassManagers = null;
			List<Map<String,Object>> roleList = null;
			//系统管理员查询业务操作员管理配置
			if ((operUser.getRank() == 1 && user.getRank() == 3)) {
				Map<String, Object> userInfo = new HashMap<String, Object>();
				userInfo.put(XmlData.USERID, user.getUserId());
				userInfo.put(XmlData.USERNAME, user.getUserName());
				userInfo.put(XmlData.SEX, user.getSex());
				userInfo.put(XmlData.EMAIL, user.getEmail());
				userInfo.put(XmlData.MOBILEID, user.getMobileId());
				userInfo.put(XmlData.TELEPHONENO, user.getTelephoneNo());
				userInfo.put(XmlData.CREATOR, user.getCreator());
				userInfo.put(XmlData.MODUSER, user.getModUser());
				userInfo.put(XmlData.RANK, user.getRank());
				userInfo.put(XmlData.REGTIME, user.getRegTime());
				userInfo.put(XmlData.MODTIME, user.getModTime());
				userInfo.put(XmlData.STATE, user.getState());
				
				UserMedia userMedia = userMediaDao.get(user.getUserId(), "4");
				if (userMedia == null) {
					throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "用户媒介不存在");
				}
				userInfo.put(XmlData.MEDIAID, userMedia.getMediaId());
				
				resMessage.put(XmlData.USER_INFO, userInfo);
				
				//获取被操作用户所在组的管理员
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.GROUPID, userGroupId.toString());
				logger.info("查询组内管理员：" + qryMap);
				managerInfoList = userDao.findAdminByGroupId(qryMap);
				logger.info("查询组内管理员返回结果：" + managerInfoList);
				if (managerInfoList == null || managerInfoList.size() == 0) {
					throw new BusinessException(RetCode.GROUP_ADMIN_NOT_EXIST, "组内管理员不存在");
				}
				User managerInfo = managerInfoList.get(0);				
				resMessage.put(XmlData.MANAGER_INFO, managerInfo);
				
				//获取被操作用户的角色
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.USERID, userId);
				logger.info("查询用户角色列表：" + qryMap);
				roleList = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户角色列表返回结果：" + roleList);
				
				//获取系统管理员下级管理员列表,不包含被操作用户所在组的管理员
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put("thisGroupId", userGroupId.toString());
				qryMap.put(XmlData.GROUPID, operUserGroupId.toString());
				logger.info("查询下级用户组管理员：" + qryMap);
				nextClassManagers = userDao.findNextClassAdminsByGroupId(qryMap);
				logger.info("查询下级用户组管理员返回结果：" + nextClassManagers);
				
				List<User> managerList = new ArrayList<User>();
				
				//如果下级管理员列表不包含所有被操作用户列表，则将其去掉
				for (Iterator<User> ir = nextClassManagers.iterator(); ir.hasNext();) {
					User manager = ir.next();
					qryMap.clear();
					qryMap.put(XmlData.SYSID, sysId);
					qryMap.put(XmlData.USERID, manager.getUserId());
					qryMap.put(XmlData.ISASSIGNABLE, "0");
					qryMap.put(XmlData.ROLETYPE, "2");
					logger.info("查询用户可授权的角色：" + qryMap);
					List<Map<String,Object>> managerAuthRoles = userRoleDao.queryUserRolesByUserId(qryMap);
					logger.info("查询用户可授权的角色返回结果：" + managerAuthRoles);
					
					boolean flag = true;
					for (Map<String, Object> role : roleList) {
						flag = false;
						for (Map<String, Object> managerRole : managerAuthRoles) {
							if (role.get(XmlData.ROLE_ID).equals(managerRole.get(XmlData.ROLE_ID))) {
								flag = true;
								break;
							}
						}
						if (!flag) {
							break;
						}
					}
					if (!flag) {
						continue;
					}
					
					managerList.add(manager);
					
				}
				
				resMessage.put(XmlData.MANAGER_LIST, managerList);
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}

			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("管理调配(查询)成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]viewUserManager响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage changeUserManager(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]changeUserManager请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.changeUserManager.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserRoleDao userRoleDao = BeanManager.getBean("userRoleDao",UserRoleDao.class);
		UserGroupDao userGroupDao = BeanManager.getBean("userGroupDao",UserGroupDao.class);
		GroupUserRelDao groupUserRelDao = BeanManager.getBean("groupUserRelDao",GroupUserRelDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			String managerId = StringUtil.trim(reqMessage.getString(XmlData.MANAGERID));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);	
			User operUser = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + user);
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			//获取被操作管理员所在的组
			logger.info("查询用户组：userId=" + userId + ",sysId=" + sysId);
			List<UserGroup> list = userGroupDao.queryList(null, userId, sysId);
			logger.info("查询用户信息返回结果：" + list);
			if (list == null || list.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "被操作用户不在任何用户组内");
			}
			Integer userGroupId = list.get(0).getUserGroupId();
			
			//获取需要调配到的管理员所在的组
			logger.info("查询用户组：userId=" + userId + ",sysId=" + sysId);
			List<UserGroup> managerList = userGroupDao.queryList(null, managerId, sysId);
			logger.info("查询用户组返回结果：" + managerList);
			if (managerList == null || managerList.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "需要调配到的管理员不在任何用户组内");
			}
			Integer managerUserGroupId = managerList.get(0).getUserGroupId();
			
			//系统管理员修改业务操作员管理配置
			if (operUser.getRank() == 1 && user.getRank() == 3) {
				if (userGroupId.equals(managerUserGroupId)) {
					throw new BusinessException(RetCode.NOT_IN_SAMEGROUP, "被操作用户和管理员不能属于同一个组");
				}
				
				//获取被操作用户的角色
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.USERID, userId);
				
				logger.info("查询用户角色列表：" + qryMap);
				List<Map<String,Object>> roleList = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户角色列表返回结果：" + roleList);
				
				//获取要调配到的管理员可分配的角色
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.USERID, managerId);
				qryMap.put(XmlData.ISASSIGNABLE, "0");
				qryMap.put(XmlData.ROLETYPE, "2");
				logger.info("查询用户可授权的角色：" + qryMap);
				List<Map<String,Object>> managerAuthRoles = userRoleDao.queryUserRolesByUserId(qryMap);
				logger.info("查询用户可授权的角色返回结果：" + managerAuthRoles);
				
				//判断被操作用户拥有的角色是否在操作用户可分配的角色范围内
				boolean flag = false;
				for (Map<String, Object> role : roleList) {
					flag = false;
					for (Map<String, Object> managerRole : managerAuthRoles) {
						if (role.get(XmlData.ROLE_ID).equals(managerRole.get(XmlData.ROLE_ID))) {
							flag = true;
							break;
						}
					}
					if (!flag) {
						throw new BusinessException(RetCode.NOT_CONTAIN_ROLES, "要调配到的管理员的角色不能包含被操作用户的所有角色");
					}
				}
				
				qryMap.clear();
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.GROUPID, managerUserGroupId.toString());
				logger.info("修改用户所属组：" + qryMap);
				groupUserRelDao.updateGroupId(qryMap);
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}

			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("管理调配(修改)成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]changeUserManager响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage lockOrUnlockUser(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]lockAndUnlockUser请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.lockAndUnlockUser.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		UserMediaDao userMediaDao = BeanManager.getBean("userMediaDao",UserMediaDao.class);
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim((String)reqMessage.get(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = StringUtil.trim((String)reqMessage.get(XmlData.USERID));
			String oprType = StringUtil.trim(reqMessage.getString(XmlData.OPRTYPE));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//查询操作用户的媒介信息
			UserMedia operUserMedia = userMediaDao.get(operUserId, "4");
			if (operUserMedia == null) {
				throw new BusinessException(RetCode.USERMEDIA_NOT_EXIST, "操作用户用户媒介不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + user);	
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			//系统管理员解锁或锁定业务管理员&&系统管理员解锁或锁定业务操作员&&业务管理员解锁或锁定业务操作员
			if ((operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3) 
					|| operUser.getRank() == 2 && user.getRank() == 3) {
				//系统管理员禁用业务管理员,业务管理员同组的操作员全部为禁用状态,才能禁用
				if (operUser.getRank() == 1 && user.getRank() == 2 && "1".equals(oprType)) {
					qryMap.clear();
					qryMap.put(XmlData.SYSID, sysId);
					qryMap.put(XmlData.USERID, userId);
					if (!userDao.isAllUserLockInGroup(qryMap)) {
						throw new BusinessException(RetCode.EXIST_NOTLOCK_USER_INGOURP, "管理员下存在未禁用的用户");
					}
				}
				
				qryMap.clear();
				//0：解锁用户 1：锁定用户
				if("0".equals(oprType)){
					qryMap.put(XmlData.STATE, "0");
				} else if ("1".equals(oprType)) {
					qryMap.put(XmlData.STATE, "1");
				} else {
					throw new BusinessException(RetCode.OPR_TYPE_ERROR, "操作类型不正确");
				}
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.MODUSER, operUserMedia.getMediaId());
				qryMap.put(XmlData.MODTIME, new Timestamp(System.currentTimeMillis()));
				logger.info("解锁或锁定用户：" + qryMap);
				userDao.updateUser(qryMap);
				
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("解锁或锁定用户成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]lockAndUnlockUser响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage resetUserPassword(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]lockAndUnlockUser请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.resetUserPassword.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String operUserId = StringUtil.trim(reqMessage.getString(XmlData.OPERUSERID));
			String userId = (String)reqMessage.get(XmlData.USERID);//系统编号
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);
			logger.info("查询用户信息返回结果：" + operUser);
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);		
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			//超级管理员重置系统管理员密码&&系统管理员重置业务管理员密码&&系统管理员重置业务操作员密码&&业务管理员重置业务操作员密码
			if ((operUser.getRank() == 0 && user.getRank() == 1) 
					|| (operUser.getRank() == 1 && user.getRank() == 2) 
					|| (operUser.getRank() == 1 && user.getRank() == 3) 
					|| operUser.getRank() == 2 && user.getRank() == 3) {
				//生成6为随机数
				String password = PasswordUtil.getRandom(6);
				//对密码行进加密	
				String cytPassword = PasswordUtil.genShaPem(password);
				
				qryMap.clear();
				qryMap.put(XmlData.USERID, userId);
				qryMap.put(XmlData.SYSID, sysId);
				qryMap.put(XmlData.PASSWORD, cytPassword);
				qryMap.put(XmlData.MODTIME, new Timestamp(System.currentTimeMillis()));
				logger.info("重置密码：" + qryMap);
				userDao.updateUser(qryMap);
				
				resMessage.put(XmlData.PASSWORD, password);
			} else {
				throw new BusinessException(RetCode.NO_PRIVILEGE, "无操作权限");
			}
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("解锁或锁定用户成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]lockAndUnlockUser响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage modify(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]modify请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.update.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim((String)reqMessage.get(XmlData.SYSID));
			String userId = StringUtil.trim((String)reqMessage.get(XmlData.USERID));//系统编号
			String userName = StringUtil.trim((String)reqMessage.get(XmlData.USERNAME));//姓名
			String email = StringUtil.trim((String)reqMessage.get(XmlData.EMAIL));//邮箱
			
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			qryMap.put(XmlData.USERNAME, userName);
			qryMap.put(XmlData.EMAIL, email);
			qryMap.put(XmlData.MODTIME, new Timestamp(System.currentTimeMillis()));
			logger.info("修改用户信息：" + qryMap);
			userDao.updateUser(qryMap);
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("修改用户信息成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]modify响应数据："+resMessage);
		return resMessage;
	}
	
	public ResMessage modifyPassword(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]modifyPassword请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.updatePassword.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		//创建报文返回对象
		ResMessage resMessage = new ResMessage();
		try {
			String sysId = StringUtil.trim((String)reqMessage.get(XmlData.SYSID));//系统编号
			String userId = StringUtil.trim((String)reqMessage.get(XmlData.USERID));//用户编号
			String oldPwd = StringUtil.trim((String)reqMessage.get(XmlData.OLD_PWD));//老密码
			String newPwd = StringUtil.trim((String)reqMessage.get(XmlData.NEW_PWD));//新密码
			
			//获取用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);		
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			String dbPwd = StringUtil.trim(user.getPassword());
			
			//判断数据库中密码和老密码是否一致
			if (!dbPwd.equals(oldPwd)) {
				throw new BusinessException(RetCode.OLD_PWD_ERROR, "原密码输入有误");
			}
			//保存新密码到数据库
			qryMap.put(XmlData.PASSWORD, newPwd);
			qryMap.put(XmlData.MODTIME, new Timestamp(System.currentTimeMillis()));
			//mupeng add 2016-10-25 21:09:39
			//增加修改密码的时间（）
			qryMap.put(XmlData.PASSWD_LASTMODIFTY_TIME, new Timestamp(System.currentTimeMillis()));
			logger.info("修改密码：" + qryMap);
			userDao.updateUser(qryMap);
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("用户修改密码成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]modifyPassword响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage queryUsersByRoleId(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]queryUsersByRoleId请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.queryUsersByRoleId.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			UserDao userDao = BeanManager.getBean("userDao", UserDao.class);
			UserGroupDao userGroupDao = BeanManager.getBean("userGroupDao",UserGroupDao.class);
			
			Short sysId = Short.parseShort(reqMessage.get(XmlData.SYSID).toString());
			Integer roleId = Integer.parseInt(reqMessage.get(XmlData.ROLE_ID).toString());
			String operUserId = StringUtil.trim((String) reqMessage.get(XmlData.OPERUSERID));
			
			//获取操作用户信息
			Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.clear();
			qryMap.put(XmlData.USERID, operUserId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询操作用户信息：" + qryMap);
			User operUser = userDao.getUser(qryMap);
			logger.info("查询操作用户信息返回结果：" + operUser);			
			if (operUser==null){
				throw new BusinessException(RetCode.NO_DATA, "操作用户不存在");
			}
			
			//获取被操作管理员所在的组
			logger.info("查询操作用户的用户组：operUserId=" + operUserId + ",sysId=" + sysId);
			List<UserGroup> operUserGrouplist = userGroupDao.queryList(null, operUserId, sysId.toString());
			logger.info("查询操作用户的用户组返回结果：" + operUserGrouplist);
			if (operUserGrouplist == null || operUserGrouplist.size() == 0) {
				throw new BusinessException(RetCode.NO_USERGROUP, "被操作用户不在任何用户组内");
			}
			Integer operUserGroupId = operUserGrouplist.get(0).getUserGroupId();
			
			//查询使用该角色使用的用户
			logger.info("查询使用该角色使用的用户：roleId=" + roleId + ",sysId=" + sysId);
			List<Map<String, Object>> userList = userDao.queryUsingUserByRoleId(roleId, sysId);
			
			//对用户列表userList进行处理，以用户组的形式将组编号和用户列表的对应关系放入resultMap中
			Map<String, List<Map<String, Object>>> resultMap = new HashMap<String, List<Map<String, Object>>>();
			if (userList != null) {
				Set<String> keySet = new HashSet<String>();
				String userGroupId = null;
				String userId = null;
				String userName = null;
				Integer rank = null;
				String mediaId = null;
				String mediaType = null;
				
				Map<String, Object> user = null;
				for (Map<String, Object> u : userList) {
					userGroupId = u.get(XmlData.USERGROUPID).toString();
					userId = StringUtil.trim((String) u.get(XmlData.USERID));
					userName = StringUtil.trim((String) u.get(XmlData.USERNAME));
					rank = (Integer) u.get(XmlData.RANK);
					mediaId = StringUtil.trim((String) u.get(XmlData.MEDIAID));
					mediaType = StringUtil.trim((String) u.get(XmlData.MEDIATYPE));
					
					user = new HashMap<String, Object>();
					user.put(XmlData.USERID, userId);
					user.put(XmlData.USERNAME, userName);
					user.put(XmlData.RANK, rank);
					user.put(XmlData.MEDIAID, mediaId);
					user.put(XmlData.MEDIATYPE, mediaType);
					
					//业务管理员只能查询自己下面的操作员
					if (operUser.getRank().equals((short) 2) && !operUserGroupId.toString().equals(userGroupId)) {
						continue;
					}
					
					if (keySet.contains(userGroupId)) {
						for (Map.Entry<String, List<Map<String, Object>>> entry : resultMap.entrySet()) {
							if (entry.getKey().equals(userGroupId)) {
								entry.getValue().add(user);
							}
						}
					} else {
						keySet.add(userGroupId);
						
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
						list.add(user);
						resultMap.put(userGroupId, list);
					}
				}
			}
			
			resMessage.put("resultMap", resultMap);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("查询角色使用情况成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		
		logger.info("[UserServiceBean]queryUsersByRoleId响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage getUserInfo(ReqMessage reqMessage) {
		logger.info("[UserServiceBean]getUserInfo请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "UserServiceBean.getUserInfo.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = StringUtil.trim(reqMessage.getString(XmlData.SYSID));
			String userId = StringUtil.trim(reqMessage.getString(XmlData.USERID));
			
			Map<String, Object> qryMap = new HashMap<String, Object>();
			
			//获取被操作用户信息
			qryMap.clear();
			qryMap.put(XmlData.USERID, userId);
			qryMap.put(XmlData.SYSID, sysId);
			logger.info("查询用户信息：" + qryMap);
			User user = userDao.getUser(qryMap);	
			logger.info("查询用户信息返回结果：" + user);			
			if (user==null){
				throw new BusinessException(RetCode.NO_DATA, "被操作用户不存在");
			}
			
			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo.put(XmlData.USERNAME, user.getUserName());
			userInfo.put(XmlData.RANK, user.getRank());
			userInfo.put(XmlData.EMAIL, user.getEmail());

			resMessage.put(XmlData.USER_INFO, userInfo);
			
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("查询用户详情成功");
		} catch (BusinessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(e.getCode());
			resMessage.setRetMsg(e.getMessage());
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[UserServiceBean]getDetail响应数据："+resMessage);
		return resMessage;
		}
	 public ResMessage getUserCountByMobileId(ReqMessage reqMessage) {
		 
		ResMessage resMessage = new ResMessage();// 创建报文返回对象
		String mobileId = StringUtil.trim(reqMessage.getString(XmlData.MOBILEID));
		try {
			// 查询手机号是否存在
			Map<String, Object> qryMapMbile = new HashMap<String, Object>();
			qryMapMbile.put(XmlData.MOBILEID, mobileId);
			int count = userDao.findPageList_count(qryMapMbile);
			resMessage.put("count", count);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("查询用户详情成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(), e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		}
		// add by bitao 2016-11-1 增加手机号校验 end
		return resMessage;
		
	}
	 public ResMessage getUsersByMobileId(ReqMessage reqMessage) {
		 
			ResMessage resMessage = new ResMessage();// 创建报文返回对象
			String mobileId = StringUtil.trim(reqMessage.getString(XmlData.MOBILEID));
			try {
				// 查询手机号是否存在
				Map<String, Object> qryMapMbile = new HashMap<String, Object>();
				qryMapMbile.put(XmlData.MOBILEID, mobileId);
				List<User> users = userDao.findPageList(qryMapMbile, 0, 10);
				for (User user : users){
				UserMedia userMedia =	userMediaDao.get(user.getUserId(), "4");
					if (userMedia!=null){
						user.setMediaId(userMedia.getMediaId());
					}
				}
				
				resMessage.put("userList", users);
				resMessage.setRetCode(RetCode.SUCCESS);
				resMessage.setRetMsg("查询用户详情成功");
			} catch (DataAccessException e) {
				logger.error(e.getMessage(), e);
				resMessage.setRetCode(RetCode.DB_ERROR);
				resMessage.setRetMsg("数据库出错");
			}
		
			return resMessage;
			
		}
}
